package siddur.traktask.framework;

import java.io.File;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;


@Component
public class ApplicationInitalizer implements ApplicationListener<ContextRefreshedEvent>{
	private static final Logger log4j = Logger.getLogger(ApplicationInitalizer.class);
	
	@PersistenceContext
	private EntityManager em;
	
	@Autowired
	private ConfigBean configBean;
	
	public void init() throws InterruptedException{
		configBean.loadConfig();
		initFS();
	}
	
	private void initFS(){
		String dir = configBean.getConfigValue(Constants.FILE_HOME);
		if(StringUtils.isNotBlank(dir)){
			log4j.info("Select File Home: " + dir);
			FileSystemUtil.setHome(new File(dir));
		}
	}
	

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		try {
			init();
		} catch (InterruptedException e) {
			log4j.error(e.getMessage(), e);
		}
	}
}
